<?php
namespace App\Repository;

use App\Model\Shop;

use App\Facade\Event;
use App\Event\Shop\{StatusEvent, CreateEvent, CheckTimeEvent};

class ShopRepository extends \HyperfStore\Repository
{
    // 放入模型
    public function build()
    {
        return new Shop;
    }
    
    // 创建
    public function create(UserRepository $user, $data)
    {
        $this->model->user()->associate($user->model());
        
        $res = $this->save($data);
        
        Event::dispatch(new CreateEvent($this));
        
        return $res;
    }
    
    // 状态
    public function setStatusOk()
    {
        $this->model->status = Shop::STATUS_OK;
        $this->model->status_time = time();
        
        $res = $this->model->save();
        
        Event::dispatch(new StatusEvent($this));
        
        return $res;
    }
    
    // 关联上级店铺
    public function setShop(ShopRepository $shop)
    {
        $this->model->shop()->associate($shop->model());
        
        return $this->model->save();
    }
    
    // 更新考核时间
    public function setCheckTime($time)
    {
        // 保存上次时间
        $this->model->last_time  = $this->model->check_time;
        
        // 起始时间
        $check_time = $this->model->check_time > 0 ? $this->model->check_time : time();
        
        $this->model->check_time = $check_time + $time;
        
        return $this->model->save();
    }
    
    // 获取业绩区间
    public function getCheckTime()
    {
        return [$this->model->last_time, $this->model->check_time];
    }
    
    // 店铺考核
    public function checkTime()
    {
        Event::dispatch(new CheckTimeEvent($this));
    }
}